package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.DbUtil;
import com.csjy.migration.hnnd.DictTool;
import com.csjy.migration.hnnd.ProgramArgument;
import com.csjy.migration.hnnd.Tool;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;
import com.csjy.migration.hnnd.dict.FileType;
import com.csjy.migration.hnnd.dict.StoreType;

import javax.script.ScriptException;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

@BusinessDataConverter(
    auto = false,
    insertSql = "INSERT INTO ND_BPM_PROJECT_ARCHIVE" +
        "          (ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS," +
        "           FILE_ENCODE, FILE_NAME, PRO_ENCODE, FILE_NUMBER, FILE_TYPE, ATTACHMENT_NAME, STORE_TYPE, CONTRACT_ENCODE, PAGE_REMARK, INFOS_ID, PRO_ID, " +
        "          FILE_STATUS, IS_PIGEONHOLE, IS_VALID, TASK_ID, PROC_ID, SOURCE_ID, TASK_DEF_KEY, TIME_OF_FILING, ARCHIVE_CATEGORY) " +
        "           VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
    updateSql = "UPDATE ND_BPM_PROJECT_ARCHIVE\n" +
        "SET CREATE_NAME=?, CREATE_BY=?, CREATE_DATE=?, UPDATE_NAME=?, UPDATE_BY=?, UPDATE_DATE=?, SYS_ORG_CODE=?, SYS_COMPANY_CODE=?, BPM_STATUS=?, FILE_ENCODE=?, FILE_NAME=?, PRO_ENCODE=?, FILE_NUMBER=?, FILE_TYPE=?, ATTACHMENT_NAME=?, STORE_TYPE=?, CONTRACT_ENCODE=?, PAGE_REMARK=?, INFOS_ID=?, PRO_ID=?, FILE_STATUS=?, IS_PIGEONHOLE=?, IS_VALID=?, TASK_ID=?, PROC_ID=?, SOURCE_ID=?, TASK_DEF_KEY=?, TIME_OF_FILING=?, ARCHIVE_CATEGORY=?" +
        "WHERE ID = ?",
    findMigratedIdListSql = "SELECT ID FROM ND_BPM_PROJECT_ARCHIVE WHERE PROC_ID = ?"
)
public class NdBpmProjectArchive extends AbstractWorkflowBusiness {

  public NdBpmProjectArchive(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId, String procInstId) throws SQLException {
    super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId, procInstId);
  }


  @Override
  public void migrate() throws Exception {
    List<Map> btItemDatumSubmitList = this.sourceData.getBtItemDatumSubmitList().stream()
        .filter(btItemDatumSubmit->{
          if(btItemDatumSubmit.get("WORKFLOWNO") == null){
            return false;
          }
          return btItemDatumSubmit.get("WORKFLOWNO").toString().equals(this.procInstId);
        })
        .collect(Collectors.toList());

    for(Map.Entry<String,Map<String,Object>> entry : taskParamMap.entrySet()) {
      String curJbpmTaskInstanceId = entry.getKey();
      Map<String,Object> taskParam = entry.getValue();

      for (Map row : btItemDatumSubmitList) {
        try {
          // 判断是否需要覆盖迁移
          int needMigratedResult = this.needMigrated(row.get("DOCNO").toString() +"-"+ curJbpmTaskInstanceId);
          if(needMigratedResult == 0) {
            continue;
          }

          // 单条插入或更新
          if(needMigratedResult == 1) {
            this.targetDbUtil.updateByParams(updateSql,this.buildValues(row, curJbpmTaskInstanceId, taskParam),true);
            // 批量插入或更新 和 单条插入或更新 二选一
//            this.batchUpdateValues.add(this.buildValues(row, curJbpmTaskInstanceId, taskParam));
          } else {
            this.targetDbUtil.updateByParams(insertSql,this.buildValues(row, curJbpmTaskInstanceId, taskParam));
            // 批量插入或更新 和 单条插入或更新 二选一
//            this.batchInsertValues.add(this.buildValues(row, curJbpmTaskInstanceId, taskParam));
          }
        } catch(Exception e) {
          throw new Exception(String.format("流程实例[%s]-任务实例[%s]-归档资料迁移失败:%s\n",this.procInstId, curJbpmTaskInstanceId, e.getMessage()));
        }
      }
    }
  }

  public List buildValues(Map row, String curJbpmTaskInstanceId, Map<String,Object> taskParam) throws ScriptException, SQLException {
      List values = new ArrayList();
      // ID
      values.add(row.get("DOCNO")+ "-"+curJbpmTaskInstanceId);
      // CREATE_NAME
      values.add(null);
      // CREATE_BY
      values.add(row.get("EMPCODE"));
      // CREATE_DATE
      values.add(row.get("CREATE_TIME"));
      // UPDATE_NAME
      values.add(null);
      // UPDATE_BY
      values.add(null);
      // UPDATE_DATE
      values.add(row.get("MODIFY_TIME"));
      // SYS_ORG_CODE
      values.add(null);
      // SYS_COMPANY_CODE
      values.add("002");
      // BPM_STATUS
      values.add(1);
      // FILE_ENCODE
      values.add(row.get("DOCCODE"));
      // FILE_NAME
      values.add(row.get("DOCNAME"));
      // PRO_ENCODE
      values.add(this.sourceData.getBtItemBasic().get(0).get("ITEMCODE"));
      // FILE_NUMBER
      values.add(row.get("PAGESPERUNIT"));
      // FILE_TYPE
      values.add(DictTool.getTargetDictCode(FileType.class,row.get("DATUMTYPE").toString()));
      // ATTACHMENT_NAME
      values.add(null);
      // STORE_TYPE
      values.add(DictTool.getTargetDictCode(StoreType.class,row.get("DOCTYPE").toString()));
      // CONTRACT_ENCODE
      values.add(row.get("CONTRACTNO"));
      // PAGE_REMARK
      values.add(row.get("DOCREMARK") == null ? null : Tool.decodeUnicode(row.get("DOCREMARK").toString()));
      // INFOS_ID
      values.add(row.get("ELEFILESTORENAME") == null ? null : row.get("ELEFILESTORENAME").toString().replace("-",""));
      // PRO_ID
      values.add(this.projectId);
      // FILE_STATUS
      values.add(row.get("EXTFLAG").toString().equals("1") ? "已提交":"待补交");
      // IS_PIGEONHOLE（是否已入档)
      values.add(taskParam.get("isPigeonhole"));
      // IS_VALID
      values.add("Y");
      // TASK_ID
      values.add(curJbpmTaskInstanceId+"-JW");
      // PROC_ID
      values.add(this.procInstId+"-JW");
      // SOURCE_ID
      values.add(row.get("DOCNO"));
      // TASK_DEF_KEY
      values.add(taskParam.get("taskDefKey"));
      // TIME_OF_FILING
      values.add(null);
      // ARCHIVE_CATEGORY
      values.add(taskParam.get("archiveCategory"));

      return values;
    }
  }
